package com.peiqi.aiproject.utils;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.http.HttpStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author yulian
 * @version 1.0
 * @description: TODO
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    // 注册 Sa-Token 全局过滤器
    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
//                去掉这个就可以显示全部内容
//                .addInclude("/**")
                .addExclude(
                        "/favicon.ico",
                        "/doc.html",
                        "/actuator",
                        "/actuator/**",
                        "*.html",
                        "*.css",
                        "*.js",
                        "/swagger-resources/**",
                        "/*/api-docs",
                        "/login",
                        "/users/registers",
                        "/chat"
                )
                // 认证函数: 每次请求执行
                .setAuth(obj -> {
                    // 登录认证
                    SaRouter.match("/**")
                            .notMatch("/login", "/users/reg","/sms","/sms/valid-sms","/register")
                            .check(r -> {
                                StpUtil.checkLogin();
                            });
                })
                .setError(nle -> {
                    if (nle instanceof NotLoginException) {
                        String type = ((NotLoginException) nle).getType();
                        String message = "";
                        if (type.equals(NotLoginException.NOT_TOKEN)) {
                            message = "未提供token";
                        } else if (type.equals(NotLoginException.INVALID_TOKEN)) {
                            message = "token无效";
                        } else if (type.equals(NotLoginException.TOKEN_TIMEOUT)) {
                            message = "token已过期";
                        } else if (type.equals(NotLoginException.BE_REPLACED)) {
                            message = "其他地点登录，已被顶下线";
                        } else if (type.equals(NotLoginException.KICK_OUT)) {
                            message = "其他地点登录，已被顶下线"; //"已被管理员踢下线";
                        } else {
                            message = "当前会话未登录";
                        }
                        return SaResult.error(message).setCode(HttpStatus.HTTP_UNAUTHORIZED);
                    } else {
                        return SaResult.error(nle.getMessage()).setCode(HttpStatus.HTTP_UNAUTHORIZED);
                    }
                });
    }
}
